// pages/visit/detail/detail.js
const serviceUrl = getApp().globalData.serviceUrl;
const QQMapKey = getApp().globalData.QQMapKey;
var visitservice = require("../../../apiservice/visit/visitservice");
var attachmentservice = require("../../../apiservice/attachment/attachmentservice");
var jsondata = require("../jsondata.js");
var QQMapWX = require("../../../utils/qqmap-wx-jssdk.min.js");
var utils = require("../../../utils/util.js");
var app = getApp();
var activityId = '';
var qqmapsdk;
Page({

	/** 
	 * 页面的初始数据
	 */
	data: {
		latitude: null,
		longitude: null,
		visitItem: {}, //拜访信息
		stateName: '', //状态名称（用于标签）
		color: '',
		labelHidden: true,
		actionHidden: false, //action-list的显示状态
		editHidden: false, //修改按钮显示状态
		imgListHidden: true, //用于控制图片列表的显示状态
		buttonHidden: true, //控制完成、签到按钮的显示状态
		finishHidden: true, //拜访目标达成情况的组件的显示状态
		photoActionHidden: false, //点击拍照按钮的模块显示状态
		visitCheckInItem: {
			activityid: null,
			new_signinplace: null,
			new_signintime: null,
			requiredattendees: null
		}, //签到的实体
		tempFilePaths: [], //图片路径数组
		imgUrl: serviceUrl + "/api/Attachment?imgName=",
		delPhotoShow: false,
		PhotoShow: true
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		//获取当前拜访id

		activityId = options.activityid;
		this.setData({
			['visitCheckInItem.activityid']: activityId
		})

		//获取定位服务
		qqmapsdk = new QQMapWX({
			key: QQMapKey
		});
		//加载图片
		this.initalImages();
	},
	/**
	 * 跳转到修改页面
	 */
	toEditPage: function() {
		//传送整个拜访对象给更新页面
		let data = JSON.stringify(this.data.visitItem);
		wx.navigateTo({
			url: '../modify/modify?data=' + data
		});
	},

	openPhotoDetail: function(e) {
		console.log(e);
		var index = e.currentTarget.dataset.index;
		var imgurl = this.data.imgUrl;
		// var imgName = this.data.tempFilePaths[e.currentTarget.dataset.index];
		// var imgsrc = imgurl+imgName+"&height=500&width=500";
		var imgArray = this.data.tempFilePaths;
		var urls = [];
		imgArray.forEach(element => {
			console.log(imgurl + element + "&height=500&width=500");
			urls.push(imgurl + element + "&height=500&width=500")
		});
		wx.previewImage({
			current: urls[index], // 当前显示图片的http链接
			urls: urls // 需要预览的图片http链接列表
		})
	},
	/**
	 * 取消拜访
	 */
	onCancelAppointment: function() {
		var statecode = 2;
		var statuscode = 4;
		var that = this;
		wx.showModal({
			title: '',
			content: '您确定要取消本次拜访吗？',
			success: function(res) {
				if (res.cancel) return;
				visitservice.UpdateAppointmentState(activityId, statecode, statuscode).then(function(res) {

					//获取标签名字
					var obj = jsondata.getStateNameByStateCode(2);
					var sName = obj.name;
					var sColor = obj.color;
					//隐藏action-list、隐藏修改按钮、改写标签
					that.setData({
						actionHidden: true,
						stateName: sName,
						editHidden: true,
						color: sColor
					})
					wx.showToast({
						title: '取消成功',
						icon: 'success',
						duration: 2000
					});
				}).catch(function(ex) {
					console.log(ex);
					wx.showToast({
						title: '取消失败，网络异常',
						icon: 'success',
						duration: 2000
					});
				})
			}
		})
	},
	/**
	 * 签到
	 */
	onCheckIn: function() {
		var that = this;
		wx.showModal({
			title: '提示',
			content: '您确定要进行本次拜访签到吗？',
			success(res) {
				if (res.confirm) {
					that.checkIn();
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}

		})
	},
	/**
	 * 显示拜访目标达成情况窗口
	 * @param {*} e 
	 */
	onOpenEditCompelete: function(e) {

		this.setData({
			finishHidden: false
		});
	},
	/**显示添加或删除图片action */
	openPhotoAction: function() {
		this.setData({
			photoActionHidden: true
		})
	},
	/**
	 * 关闭拜访目标达成情况窗口
	 */
	onClose: function() {
		this.setData({
			finishHidden: true,
			['visitItem.new_descripion']: null
		});
	},
	/**关闭图片action */
	onPhotoClose: function() {
		this.setData({
			photoActionHidden: false
		})
	},
	/** */
	onPhotoSelect: function(e) {
		//console.log(e);
		var index = e.detail.id;
		if (index == 1) {
			//打开图片选择
			this.openCamera();
		} else if (index == 2) {
			//删除图片			
			this.setData({
				delPhotoShow: true,
				photoActionHidden: false
			})
		}
	},

	/**
	 * 拜访目标达成情况文本赋
	 */
	onDescriptionChange: function(e) {

		this.setData({
			['visitItem.new_descripion']: e.detail.value
		});
	},
	/**
	 * 完成
	 */
	onSubmit: function() {
		var that = this;
		var description = this.data.visitItem.new_descripion;
		if (description) {
			wx.showModal({
				title: '提示',
				content: '您确定要完成本次拜访吗？',
				success(res) {
					if (res.confirm) {
						that.finishVisit();
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}

			})
		} else {
			wx.showToast({
				title: '请填写拜访目标达成情况',
				icon: 'none'
			})
		}
	},
	finishVisit: function() {
		var that = this;
		visitservice.CompeleteAppointment(this.data.visitItem).then(function(success) {
			console.log(success)
			var obj = jsondata.getStateNameByStateCode(1);
			var sName = obj.name;
			var sColor = obj.color;
			that.setData({
				actionHidden: true,
				editHidden: true,
				['visitItem.statecode']: 1,
				stateName: sName,
				finishHidden: true,
				color: sColor,
				labelHidden: false
			})
			wx.showToast({
				title: '拜访已完成',
				icon: 'success',
				duration: 2000
			});
		}).catch(function(ex) {
			console.log(ex);
			wx.showToast({
				title: '失败，网络异常',
				duration: 2000
			});
		})
	},
	/**上传图片 */
	openCamera: function() {
		var that = this;
		var imgs = this.data.tempFilePaths;
		var token = wx.getStorageSync('token');
		var imageCount = 5;
		if (imgs.length >= imageCount) {
			wx.showToast({
				title: '最多只能选择5张照片',
				icon: 'none',
				duration: 1500,
				success(res) {
					that.setData({
						photoActionHidden: false
					})
				}
			})

			return;
		}
		wx.chooseImage({
			count: imageCount - imgs.length,
      sizeType: ['original','compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				// tempFilePath可以作为img标签的src属性显示图片
				//const tempFilePaths = res.tempFilePaths
				for (var i = 0; i < res.tempFilePaths.length; i++) {
					var imagename = res.tempFilePaths[i].substring(res.tempFilePaths[i].lastIndexOf('/') + 1)
					imgs.push(imagename);
					wx.uploadFile({
						url: serviceUrl + '/api/Attachment/PostAttachment',
						header: {
							'Authorization': 'Bearer ' + token
						},
						filePath: res.tempFilePaths[i],
						formData: {
							//name: "test",
							entityId: activityId
						},
						name: 'file',
						success(success) {
							that.setData({
								photoActionHidden: false,
								tempFilePaths: imgs
							})
							//do something
						},
						fail(error) {
							console.log(error);
						}
					})

					//console.log(res.tempFilePaths[i]);
				};
			}
		});
	},
	/**
	 * 删除图片
	 */
	delPhoto: function(e) {

		var that = this;
		var index = e.currentTarget.dataset.index;
		var imgPath = this.data.tempFilePaths[index];
		var tempFilePaths = this.data.tempFilePaths;
		wx.showModal({
			title: '',
			content: '是否删除该图片？',
			success(res) {
				console.log(res);
				if (res.cancel) return false;
				tempFilePaths.splice(index, 1)
				that.DelAttachment(imgPath);
				that.setData({
					tempFilePaths: tempFilePaths,
					delPhotoShow: false
				})
			}
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		//加载拜访信息
		this.getVisitItemById();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	/**
	 * 获取拜访信息
	 */
	getVisitItemById() {

		var that = this;
		visitservice.GetAppointmentById(activityId).then(function(success) {
			console.log(success);
			//获取标签名字
			var obj = jsondata.getStateNameByStateCode(success.data.statecode)
			var sName = obj.name;
			var sColor = obj.color;
			var requiredattendees = [];
			requiredattendees.push(success.data.requiredattendees);
			if (success.data != null) {
				var statecode = success.data.statecode;
				var subject = success.data.subject
				var new_visitpurpose = success.data.new_visitpurpose
				//console.log(statecode);
				//控制签到、取消、完成标签以及修改按钮的显示
				if (statecode != 0 && statecode != 3) {
					that.setData({
						actionHidden: true,
						editHidden: true,
					})
				}
				//控制完成标签，图片列表的出现
				if (statecode == 3) {
					that.setData({
						buttonHidden: false,
						imgListHidden: false
					})
				}
				if (statecode == 1) {
					that.setData({
						labelHidden: false
					})
				}
			}
			console.log(requiredattendees);
			that.setData({
				stateName: sName,
				color: sColor,
				visitItem: success.data,
				['visitItem.requiredattendees']: requiredattendees,
				['visitCheckInItem.requiredattendees']: requiredattendees,
				['visitCheckInItem.subject']: subject,
				['visitCheckInItem.new_visitpurpose']: new_visitpurpose
			});
			
			//debugger;
			
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	/**
	 * 获取当前地点、日期签到
	 */
	checkIn: function() {
		var that = this;
		//获取签到位置
		wx.getLocation({
			success: function(res) {
				that.getMapAddress(res, that);
			},
			fail: function() {
				wx.getSetting({
					success: function(res) {
						var statu = res.authSetting;
						if (!statu['scope.userLocation']) {
							wx.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权',
								success: function(tip) {
									if (tip.confirm) {
										wx.openSetting({
											success: function(data) {
												if (data.authSetting["scope.userLocation"] === true) {
													wx.showToast({
														title: '授权成功',
														icon: 'none',
														duration: 1000
													})
													wx.getLocation({
														success: function(res) {
															that.getMapAddress(res.that);
														}
													})
												} else {
													wx.hideLoading();
													wx.showToast({
														title: '授权失败',
														icon: 'none',
														duration: 1000
													})
												}
											}
										})
									}else{
										wx.hideLoading();
									}
								}
							})
						}
					},
					fail: function(res) {
						wx.showToast({
							title: '调用授权窗口失败',
							icon: 'none',
							duration: 1000
						})
					}
				})
			}
		})
	},

	/**
	 *调用签到api
	 */
	getMapAddress: function(res, that) {
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: res.latitude,
				longitude: res.longitude
			},
			coord_type: 1,
			success: function(success) {
				console.log(success)
				var address = success.result.address;
				var currentTime = utils.formatTime(new Date());
				that.setData({
					['visitItem.new_signinplace']: address,
					['visitItem.new_signintime']: currentTime,
					['visitCheckInItem.new_signinplace']: address,
					['visitCheckInItem.new_signintime']: currentTime
				});
				//改写状态
				that.getCheckInAppointment(that);
			}
		})
	},

	getCheckInAppointment: function(that) {
		//console.log(that.data.visitCheckInItem);
		//签到
		visitservice.CheckIn(that.data.visitCheckInItem).then(function(success) {
			console.log(success);
			//获取标签名字,3 代表进行中
			var obj = jsondata.getStateNameByStateCode(3)
			var sName = obj.name;
			var sColor = obj.color;
			//签到完成，改写action-list，改写标签
			that.setData({
				stateName: sName,
				color: sColor,
				['visitItem.statecode']: 3,
				imgListHidden: false,
				buttonHidden: false
			})
			wx.showToast({
				title: '签到成功'
			})
		}).catch(function(ex) {
			console.log(ex);
			wx.showToast({
				title: '签到失败',
				icon: 'none'
			})
		})
	},
	initalImages: function() {
		var that = this;
		attachmentservice.GetImgAtachments(activityId).then(function(success) {
			debugger;
			that.setData({
				tempFilePaths: success.data,
				imgListHidden: false
			})
			
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	DelAttachment: function(dir) {
		attachmentservice.DelAttachment(dir).then(function(success) {
			console.log(success.data);
		}).catch(function(ex) {
			console.log(ex);
		})
	}

})
